<?php

namespace app\shop\model\info;

use app\common\model\info\Info as InfoModel;
use app\shop\model\menu\Menu as MenuModel;

/**
 * 内容模型
 */
class Info extends InfoModel
{
    /**
     * 获取列表
     */
    public function getList($param)
    {
        $model = $this;
        if (isset($param['menu_id']) && $param['menu_id']) {
            $model = $model->where('menu_id', '=', $param['menu_id']);
        }
        if (isset($param['title']) && $param['title']) {
            $model = $model->where('title', 'like', '%' . $param['title'] . '%');
        }
        $list = $model->with(['menu', 'mould'])
            ->where('is_delete', '=', 0)
            ->order(['sort' => 'asc', 'create_time' => 'desc'])
            ->paginate($param);
        return $list;
    }

    /**
     * 添加内容
     */
    public function add($data)
    {
        $data['app_id'] = self::$app_id;
        // 开启事务
        $this->startTrans();
        try {
            $menuInfo = MenuModel::detail($data['menu_id']);
            $data['mould_id'] = $menuInfo['mould_id'];
            $data['app_id'] = self::$app_id;
            // 添加内容
            $this->save($data);
            // 图片集
            if (isset($data['images']) && $data['images']) {
                $data['images'] && $this->addImages($data['images']);
            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 添加图片
     */
    private function addImages($images)
    {
        $this->images()->delete();
        $data = array_map(function ($images) {
            return [
                'file_path' => $images['file_path'],
                'app_id' => self::$app_id
            ];
        }, $images);
        return $this->images()->saveAll($data);
    }

    /**
     * 编辑内容
     */
    public function edit($data)
    {
        return $this->transaction(function () use ($data) {
            $menuInfo = MenuModel::detail($data['menu_id']);
            $data['mould_id'] = $menuInfo['mould_id'];
            $data['app_id'] = self::$app_id;
            // 保存商品
            $this->save($data);
            // 图片集
            if (isset($data['images']) && $data['images']) {
                $data['images'] && $this->addImages($data['images']);
            }
            return true;
        });
    }

    /**
     * 修改状态
     */
    public function setStatus($state)
    {
        return $this->save(['status' => $state]) !== false;
    }

    /**
     * 软删除
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 获取内容总数
     */
    public function getProductTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }


}
